import requests
import os
import string
import random

# 配置参数
FILE_PATH = "original_doc/old/老公称呼.txt"  # 替换为你的本地文件路径
API_KEY = "sk-8b6df4e170964def8f553aca15442d42"  # 替换为你的DeepSeek API密钥
MODEL_NAME = "deepseek-chat"  # 使用的模型名称
API_URL = "https://api.deepseek.com/v1/chat/completions"  # DeepSeek API端点


def generate_filename_with_prefix(file_path, length=8, extension="txt"):
    """使用输入文件名的点前部分作为前缀生成随机文件名"""
    # 从文件路径中提取文件名（不带路径）
    base_name = os.path.basename(file_path)

    # 提取点（.）前部分作为前缀
    if '.' in base_name:
        # 获取最后一个点之前的部分
        prefix = base_name.rsplit('.', 1)[0]
    else:
        prefix = base_name

    # 生成随机小写字母后缀
    letters = string.ascii_lowercase
    random_suffix = ''.join(random.choice(letters) for _ in range(length))

    return f"{prefix}_{random_suffix}.{extension}"

def read_file_content(file_path):
    """读取本地文件内容"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except FileNotFoundError:
        print(f"错误：文件未找到 - {file_path}")
        return None
    except Exception as e:
        print(f"读取文件时出错: {str(e)}")
        return None


def generate_content_with_deepseek(prompt, api_key, model=MODEL_NAME):
    """使用DeepSeek API生成内容"""
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    payload = {
        "model": model,
        "messages": [
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.7,
        "max_tokens": 2000
    }

    try:
        response = requests.post(API_URL, json=payload, headers=headers)
        response.raise_for_status()  # 检查HTTP错误

        result = response.json()
        return result['choices'][0]['message']['content']

    except requests.exceptions.RequestException as e:
        print(f"API请求失败: {str(e)}")
    except KeyError:
        print("API响应格式错误")
    except Exception as e:
        print(f"处理时发生错误: {str(e)}")
    return None


def main():
    # 1. 读取文件内容
    file_content = read_file_content(FILE_PATH)
    if not file_content:
        return

    print(f"已成功读取文件内容，长度: {len(file_content)}字符")

    # 2. 构建提示词（根据需要修改）
    prompt = f"""
请根据以下文件内容执行任务。文件内容如下：
-------------------------
{file_content}
-------------------------
修改文件，比如，大猪蹄子🐷：嘴上说着不管我，却偷偷把我购物车清空的口是心非大师，改成：嘴上说着不管我，却偷偷把我购物车清空的口是心非大师，大猪蹄子🐷。
"""

    # 3. 调用DeepSeek API
    print("正在调用DeepSeek API生成内容...")
    generated_content = generate_content_with_deepseek(prompt, API_KEY)

    # 4. 输出结果
    if generated_content:
        print("\n生成结果:")
        print("=" * 50)
        print(generated_content)
        print("=" * 50)

        # 生成随机文件名并保存结果
        output_filename = generate_filename_with_prefix(FILE_PATH)
        with open(output_filename, "w", encoding="utf-8") as f:
            f.write(generated_content)
        print(f"结果已保存到 {output_filename}")


if __name__ == "__main__":
    main()